package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BasePlan;
import com.yegs.jltqc.VO.BaseQuota;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.dao.BasePlanRepository;
import com.yegs.jltqc.dao.BaseQuotaRepository;
import com.yegs.jltqc.service.BasePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BasePlanServiceImpl implements BasePlanService {

    @Autowired
    private BaseQuotaRepository baseQuotaRepository;

    @Autowired
    private BasePlanRepository basePlanRepository;

    @Override
    public void save(BasePlan basePlan) throws StoreException {
        basePlan.setName(basePlan.getName().trim());
        BasePlan plan = basePlanRepository.findBasePlansByName(basePlan.getName());
        if(plan != null){
            throw new StoreException("项目名称已存在");
        }
        basePlanRepository.save(basePlan);
    }

    @Override
    public List<BasePlan> list() {
        return basePlanRepository.findAll();
    }

    @Override
    public BasePlan get(Long id) {
        return basePlanRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        List<BaseQuota> list = baseQuotaRepository.findBaseQuotasByRefId(id);
        if(list.size() > 0){
            throw new StoreException("指标已引用,不可删除");
        }
        basePlanRepository.deleteById(id);
    }

    @Override
    public Page<BasePlan> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return basePlanRepository.findAll(request);
        }
        return basePlanRepository.findBasePlansByName(query.getName(), request);
    }

}


